package com.xavier.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xavier.vo.QueryResultVO;
import com.xavier.utils.BeanUtil;
import com.xavier.utils.ServiceException;
import com.xavier.result.ResultCode;
import com.xavier.convertor.MenuConvertor;
import com.xavier.dto.MenuQueryDTO;
import com.xavier.model.Menu;
import com.xavier.dto.MenuDTO;
import com.xavier.vo.MenuPageVO;
import com.xavier.vo.MenuDetailVO;
import com.xavier.dao.MenuMapper;
import com.xavier.service.IMenuService;
import com.xavier.utils.XavierLambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.List;


/**
 * 业务逻辑层-菜单实现类
 *
 * @author Xavier
 * @version 1.0
 */
@Slf4j
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Override
    public Map<String, Object> getUserMenu() {
        // todo 根据用户绑定角色查询菜单
        List<Menu> list = list(Menu.gw().eq(Menu::getIsEnable, 1));
        return MenuConvertor.toMap(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMenu(Long id) {
        getBaseMenu(id);
        return super.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMenu(MenuDTO dto) {
        Menu menu = MenuConvertor.toMenu(dto);
        menu.setId(null);
        super.save(menu);
        return menu.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMenu(MenuDTO dto) {
        getBaseMenu(dto.getId());
        Menu menu  = MenuConvertor.toMenu(dto);
        return super.updateById(menu);
    }

    @Override
    public MenuDetailVO getMenu(Long id) {
        return MenuConvertor.toMenuDetailVO(getBaseMenu(id));
    }


    @Override
    public Menu getBaseMenu(Long id) {
        Menu menu = super.getById(id);
        if(Objects.isNull(menu) || menu.getIsDeleted()) {
            throw new ServiceException(ResultCode.COMMON_MESSAGE, "菜单不存在");
        }
        return menu;
    }

    @Override
    public List<MenuPageVO> queryMenu(MenuQueryDTO queryDTO) {
        XavierLambdaQueryWrapper<Menu> wrapper = Menu.gw();
        wrapper.eqIfPresent(Menu::getMenuType, queryDTO.getMenuType());
        wrapper.likeIfPresent(Menu::getMenuCode, queryDTO.getMenuCode());
        wrapper.likeIfPresent(Menu::getMenuName, queryDTO.getMenuName());
        List<Menu> list = super.list(wrapper);
        return MenuConvertor.toMenuPageVOList(list);
    }

}
